package com.example.first.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.example.first.interceptors.GlobalHeaderInterceptor;
import com.example.first.interceptors.UnauthorizedInterceptor;
import com.example.first.services.ApiService;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

public class RetrofitClient {

    private static final String BASE_URL = "http://10.129.131.50:8080/";
    private static Retrofit retrofit = null;
    private static Context context;
    private static String token;
    //持久化存储token
    private static SharedPreferences preferences;

    public static void init(Context context) {
        RetrofitClient.context = context;
        preferences = context.getSharedPreferences("token", Context.MODE_PRIVATE);
    }
    public static void  setToken(String tk){
        preferences.edit().putString("token",tk).commit();
    }
    public static String getToken(){
        return preferences.getString("token",null);
    }

    public static Retrofit getRetrofit() {
        if (retrofit == null) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);//日志等级

            OkHttpClient client = new OkHttpClient.Builder()
                    .addInterceptor(loggingInterceptor)//配置日志
                    .addInterceptor(new UnauthorizedInterceptor(context))
                    .addInterceptor(new GlobalHeaderInterceptor())//添加请求头
                    .build();

            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }


    public static ApiService getApiService() {
        return getRetrofit().create(ApiService.class);
    }
}
